/*
   Copyright (C) 2009 Xizhi Zhu.  All Rights Reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
   3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
   OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
   OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "p2p-tracker.h"

using namespace std;

static class P2PTrackerClass : public TclClass
{
public:
    P2PTrackerClass() : TclClass("Application/P2P/Tracker") {}
    TclObject* create(int argc, const char*const* argv)
    {
        return (new P2PTracker((Node*)TclObject::lookup(argv[4])));
    }
} class_p2p_tracker;


P2PTracker::P2PTracker(Node* node): RealApplication(node)
{
}

void P2PTracker::recv(ADU* packet, nsaddr_t src)
{
    P2PPacket* p = dynamic_cast<P2PPacket*>(packet);

    switch (p->type_)
    {
        case PktTypeRegRequest:
            // registration request from server/client
            handleRegRequest(p);
            break;

        case PktTypeUnregRequest:
            // unregistration request
            handleUnregRequest(p);
            break;

        case PktTypeNodeListRequest:
            // request for node list
            handleListRequest(p);
            break;

        default:
            break;
    }

    delete packet;
}

void P2PTracker::handleRegRequest(P2PPacket* packet)
{
    nsaddr_t id = packet->id_;

    // put the node into the list
    // if it's already in the list, do nothing
    if (packet->isServer_)
    {
        // see if it's already registered
        int size = server_list_.size();
        for (int i = 0; i < size; i++)
        {
            if (server_list_[i] == id)
            {
                return;
            }
        }

        server_list_.push_back(id);
    }
    else
    {
        // see if it's already registered
        int size = peer_list_.size();
        for (int i = 0; i < size; i++)
        {
            if (peer_list_[i] == id)
            {
                return;
            }
        }

        peer_list_.push_back(id);
    }

    // send the registration reply
    P2PPacket* reply = new P2PPacket(PktTypeRegReply);
    reply->id_ = node_->address();
    send(reply, id);
}

void P2PTracker::handleUnregRequest(P2PPacket* packet)
{
    nsaddr_t id = packet->id_;

    // delete the node from the list
    if (packet->isServer_)
    {
        int size = server_list_.size();
        for (int i = 0; i < size; i++)
        {
            if (server_list_[i] == id)
            {
                server_list_.erase(server_list_.begin() + i);;
            }
        }
    }
    else
    {
        int size = peer_list_.size();
        for (int i = 0; i < size; i++)
        {
            if (peer_list_[i] == id)
            {
                peer_list_.erase(peer_list_.begin() + i);;
            }
        }
    }
}

void P2PTracker::handleListRequest(P2PPacket* packet)
{
    P2PPacket* p = new P2PPacket(PktTypeNodeListReply);
    p->id_ = node_->address();

    // do we need to check if the peer is already registered?

    // TODO choose the list of servers/clients returned here
    p->server_list_ = server_list_;
    p->peer_list_ = peer_list_;

    send(p, packet->id_);
}

